﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Authentication;

namespace MyMessenger.Core.Services.Impl
{
    public class SecurityService : ISecurityService
    {
        private IUserService service;

        public SecurityService(IUserService service)
        {
            this.service = service;
        }

        public User Authenticate(string username, string password, string ipAddress)
        {
            User u = service.Find(username);

            //temporary user
            if (u == null && string.IsNullOrEmpty(password))
            {
                u = new User();
                u.Name = username;
                service.Save(u);
            }


            if (u == null)
                throw new AuthenticationException("Invalid username and/or password.");

            if (!CheckPassword(password, u.Password))
                throw new AuthenticationException("Invalid username and/or password.");

            service.MarkUserResponse(u);
            return u;
        }

        private bool CheckPassword(string password, string hash)
        {
            return password == hash;
        }

        public User ReValidate(int id)
        {
            User u = service.Find(id);
            if (u==null)
                throw new Exception("User not found.");

            service.MarkUserResponse(u);
            return u;
        }
    }
}
